package com.hqsj.config;

import com.github.sd4324530.fastweixin.api.CustomAPI;
import com.github.sd4324530.fastweixin.api.config.ApiConfig;
import com.hqsj.service.BeanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * Created by huangying on 2017/4/13.
 */
@Component
public class BeanFactory {

    @Autowired
    private ApplicationContext context;

    public void updateWeixinConfig(String appID, String appSecret, String appName) {
        //获取beanFactory
        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) context.getAutowireCapableBeanFactory();

        //创建bean信息
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(ApiConfig.class);
        beanDefinitionBuilder.addPropertyValue("appid", appID);
        beanDefinitionBuilder.addPropertyValue("secret", appSecret);
        //动态注册bean
        defaultListableBeanFactory.registerBeanDefinition("apiConfig", beanDefinitionBuilder.getBeanDefinition());
    }

    public void createBean(String name) {
        //获取beanFactory
        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) context.getAutowireCapableBeanFactory();

        //创建bean信息
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(BeanService.class);
        beanDefinitionBuilder.addPropertyValue("name", name);

        //动态注册bean
        defaultListableBeanFactory.registerBeanDefinition("beanService", beanDefinitionBuilder.getBeanDefinition());
    }

    public BeanService beanService() {
        return context.getBean(BeanService.class);
    }

    public ApiConfig apiConfig() {
        return context.getBean(ApiConfig.class);
    }

    public CustomAPI customAPI() {
        return new CustomAPI(apiConfig());
    }

}
